package com.alpha.gateway.utils;

import com.alpha.core.http.Response;
import com.alpha.core.utils.JsonUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author chenruwan
 * @since 2022-01-01
 */
public class ResponseUtil {
    private ResponseUtil() {
    }

    public static Mono<Void> response(ServerWebExchange exchange, HttpStatus status, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(status);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body = JsonUtil.toString(Response.failure(status.value(), message));
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes());
        return response.writeWith(Flux.just(buffer));
    }
}
